import React, { useEffect, useRef } from 'react';
import styles from './index.less';
import { viewUtils, buildingUtils, jsapi } from '@/utils/arcgis';
import { connect } from 'dva';
import synchronizeViews from '@/components/widgets/Compareview/synchronizeViews';
import CompareTitle from './title';
import layerCreator from '@/utils/arcgis/layer/layer-creator';
import { inExpression, likeExpression } from '@/utils/definitionExpressionHelper.js';

/**
 * 渲染bim 模型
 * @param _bimList 传单个渲染并goto， 传数组只渲染
 * @param goto 无需使用
 */

async function renderBimLayer(_bimList, goto = false) {
  if (!Array.isArray(_bimList)) {
    return renderBimLayer([_bimList], 'gotoLyr');
  }
  _bimList.forEach(async (m, i) => {
    if (!m.url) return;
    const lyr = await layerCreator.create({
      type: 'building',
      url: m.url,
      title: m.name,
    });

    // const view = await viewUtils.isViewReady();
    const view = window.agsGlobal2.view;
    buildingUtils.setFullModel(lyr);
    // if (goto) {
    //   lyr.when(() => {
    //     view.goTo(lyr.fullExtent);
    //   });
    // }

    // todo 临时
    lyr.when(() => {
      function hideBuildingComponent(layer) {
        if (layer.type === 'building-component' && layer.modelName == 'GenericModel') {
          layer.definitionExpression = `FamilyType not in ('桥台处伸缩缝剪切','桥台处伸缩缝','桥台处伸缩缝剪切 2') `;
        }
      }

      lyr.allSublayers.forEach(hideBuildingComponent);
    });

    view.map.add(lyr);
  });
}

// 初始化用户自定义图层
async function initCustomTileLayer(tileLayers) {
  const [TileLayer] = await jsapi.load(['esri/layers/TileLayer']);
  await viewUtils.isViewReady();

  // var googleTileLayer = new TileLayer({
  //   url: 'https://portal.wccg.tech:9002/to443/server1/rest/services/Hosted/google0722/MapServer',
  //   title: 'googleLayer',
  // });
  setTimeout(() => {
    const layers = tileLayers.map(e => {
      return new TileLayer(e);
    });
    window.agsGlobal2.view.map.addMany(layers);
  }, 300);
}

window.agsGlobal2 = {};

// 渲染进度的功能
const CompareView = ({
  dispatch,
  leftlicolor,
  compareState,
  // currentBimVersion,
  projProgressBeforeActualList,
  bimList,
  addedBimNameList,
  tileLayers,
}) => {
  const sceneDomRef = useRef();

  const sceneViewRef = useRef(null);
  const interactMapWatcher = useRef(null);
  const interactSceneWatcher = useRef(null);
  const sceneViewEventRef = useRef(null);
  const mapViewEventRef = useRef(null);
  const timer1 = useRef(null);
  const timer2 = useRef(null);

  // 初始化操作
  useEffect(() => {
    viewUtils.isViewReady().then(createView);

    //创建对比用的SceneView

    async function createView(mapview) {
      const basemap = await viewUtils.createBasemap(window.basemapConfig[1]);
      const param = {
        container: sceneDomRef.current,
        basemap: basemap,
        camera: window.appcfg.jsapiConfig.initialCamera,
      };
      // 初始化场景
      sceneViewRef.current = await viewUtils.initSceneView(param);
      window.agsGlobal2.view = sceneViewRef.current;
      synchronizeViews([window.agsGlobal.view, window.agsGlobal2.view]);
    }

    return () => {
      // 组件解除挂载清除事件监听
      interactMapWatcher.current && interactMapWatcher.current.remove();
      interactSceneWatcher.current && interactSceneWatcher.current.remove();
      sceneViewEventRef.current && sceneViewEventRef.current.remove();
      mapViewEventRef.current && mapViewEventRef.current.remove();
      clearTimeout(timer1.current);
      clearTimeout(timer2.current);

      if (sceneViewRef.current) sceneViewRef.current.container = null;
    };
  }, []);

  // 根据是否启用分屏功能 添加或者清除事件监听
  useEffect(() => {
    if (!compareState && sceneViewEventRef.current && mapViewEventRef.current) {
      // 功能关闭接触事件监听  监听compare触发
      interactMapWatcher.current.remove();
      interactSceneWatcher.current.remove();
      sceneViewEventRef.current.remove();
      mapViewEventRef.current.remove();
      clearTimeout(timer1.current);
      clearTimeout(timer2.current);
    } else if (sceneViewRef.current) {
      const mapview = window.agsGlobal.view;
      interactMapWatcher.current && interactMapWatcher.current.remove();
      interactSceneWatcher.current && interactSceneWatcher.current.remove();
      sceneViewEventRef.current && sceneViewEventRef.current.remove();
      mapViewEventRef.current && mapViewEventRef.current.remove();
      timer1.current && clearTimeout(timer1.current);
      timer2.current && clearTimeout(timer2.current);
    }

    // todo
    if (compareState) {
      renderBimLayer(bimList);
      window.agsGlobal2.view.goTo(window.agsGlobal.view.extent);
    }
  }, [compareState]);

  // 根据时间节点前的真实收工日期渲染模型
  useEffect(() => {
    renderBeforePlan(
      projProgressBeforeActualList.map(e => e.wbs),
      'WBS编码',
    );
  }, [projProgressBeforeActualList]);

  useEffect(() => {
    if (!tileLayers.length || !window.agsGlobal2.view) {
      return;
    }
    initCustomTileLayer(tileLayers);
  }, [tileLayers, window.agsGlobal2]);

  // refresh Model
  function backmaprender() {
    // buildingUtils.refresh(window.agsGlobal2.view, currentBimVersion.name);
    // buildingUtils.refresh(window.agsGlobal.view, currentBimVersion.name);
    // buildingUtils.refresh(window.agsGlobal2.view, '长沙涌水闸');
    // buildingUtils.refresh(window.agsGlobal.view, '长沙涌水闸');
    dispatch({
      type: 'construction/setLeftlicolor',
      payload: !leftlicolor,
    });
  }

  // 获取当前加载的bim模型列表
  async function getAddedBimModelsLayers() {
    const view = window.agsGlobal2.view;
    if (!view) {
      return [];
    }
    window.agsGlobal2.view.popup.close();
    return addedBimNameList.reduce((r, layerName) => {
      const lyr = view.map.layers.find(l => l.title === layerName);
      if (lyr) r.push(lyr);
      return r;
    }, []);
  }

  // 渲染时间节点前节点前的内容
  async function renderBeforePlan(values = [], sqlField = '') {
    let _definitionExpression;
    if (values === null) {
      _definitionExpression = `FamilyType not in ('桥台处伸缩缝剪切','桥台处伸缩缝','桥台处伸缩缝剪切 2') `;
    } else if (!values.length) {
      _definitionExpression = `WBS编码 in ('占位占位')`;
    } else {
      _definitionExpression = likeExpression(sqlField, values);
      // _definitionExpression = values.reduce((r, current, i) => {
      //   r += `${sqlField} like '${current}%'`;
      //   if (i == values.length - 1) {
      //     r += ' ';
      //   } else {
      //     r += ' or ';
      //   }
      //   return r;
      // }, '');
    }

    console.log(_definitionExpression, 'view2');
    const layers = await getAddedBimModelsLayers();

    layers.forEach(lyr => {
      lyr.when(() => {
        function hideBuildingComponent(subLayer) {
          // 过滤模型
          if (subLayer.type === 'building-component') {
            subLayer.definitionExpression = _definitionExpression;
          }
        }
        lyr.allSublayers.forEach(hideBuildingComponent);
      });
    });
  }

  return (
    <div className={compareState ? styles.wrapper : styles.hide}>
      <div className={styles.centerline}></div>
      <div ref={sceneDomRef} className={styles.sceneView + ' proj-view'}>
        <div
          className={styles.backbtn}
          style={{
            display: compareState ? 'block' : 'none',
          }}
          onClick={backmaprender}
        >
          {' '}
          还原
        </div>
      </div>
      <CompareTitle />
    </div>
  );
};

export default connect(({ construction, bimmodel, kanban, app }) => {
  return {
    leftlicolor: construction.leftlicolor,
    compareState: bimmodel.compareState,
    addedBimNameList: bimmodel.addedBimNameList,
    projProgressBeforeActualList: kanban.projProgressBeforeActualList,
    // currentBimVersion: bimmodel.currentBimVersion,
    bimList: bimmodel.bimList,
    tileLayers: app.tileLayers,
  };
})(CompareView);
